package com.pda.common.pages.codereplace;

import android.content.Context;
import com.apkfuns.logutils.LogUtils;
import com.pda.common.basemvp.model.BaseModel;
import com.pda.common.bean.BaseBean;
import com.pda.common.beanin.CodeReplacrInBean;
import com.pda.common.tools.StringProcess;
import com.pda.common.utils.PDAUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class CodeReplaceModelImpl extends BaseModel implements CodeReplaceModel {
    private String tag = "CodeResetModelImpl";
    private BaseBean baseBean = null;

    public CodeReplaceModelImpl(Context context) {
        super(context);
    }

    @Override
    public void codeReplace(CodeReplacrInBean codeReplacrInBean, final CallBack callBack) {
        try {
            RequestBody body = RequestBody.create(PDAUtil.JSON, gson.toJson(codeReplacrInBean));
            httpConfig.codeReplace(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            callBack.ontip("数码替换成功");
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (baseBean.getErrmsg() != null && baseBean.getErrmsg().length() > 0) {
                                callBack.ontip(baseBean.getErrmsg());
                            } else {
                                callBack.ontip(PDAUtil.connectError);
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            LogUtils.w(StringProcess.responsetoString(abBean));
                            baseBean = gson.fromJson(StringProcess.responsetoString(abBean), BaseBean.class);
                            if (baseBean != null && baseBean.getErrcode() == 0) {
                                onComplete();
                            }
                            else {
                                onError(new Throwable());
                            }
                        }
                    });
        } catch (Exception e) {
            callBack.ontip(PDAUtil.connectError);
            e.printStackTrace();
        }
    }
}

